package demo.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Date;
import java.util.Map;

/**
 * 简易缓存工具类
 */
public class CacheUtil {
    private static JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    private static String host = SystemConfigUtil.getProperties("redis.host", "dev001");
    private static int port = Integer.parseInt(SystemConfigUtil.getProperties("redis.port", "6379"));
    private static int timeout = Integer.parseInt(SystemConfigUtil.getProperties("redis.timeout", "2000"));
    private static String password = SystemConfigUtil.getProperties("redis.password", "");
    private static int database = Integer.parseInt(SystemConfigUtil.getProperties("redis.database", "9"));
    private static JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password, database);

    public static void set(String key, String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(key, value);
        }
    }

    public static String get(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            if (jedis.exists(key)) {
                return jedis.get(key);
            }
            return null;
        }
    }

    public static void hset(String key, Map<String, String> map) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hmset(key, map);
        }
    }

    public static void hset(String key, String field, String value) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.hset(key, field, value);
        }
    }

    public static Map<String, String> hget(String key) {
        try (Jedis jedis = jedisPool.getResource()) {
            if (jedis.exists(key)) {
                return jedis.hgetAll(key);
            }
            return null;
        }
    }

    public static String hget(String key, String field) {
        try (Jedis jedis = jedisPool.getResource()) {
            if (jedis.hexists(key, field)) {
                return jedis.hget(key, field);
            }
            return null;
        }
    }

    public static void expire(String key, int seconds) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.expire(key, seconds);
        }
    }

    public static void expireAt(String key, Date expireDate) {
        try (Jedis jedis = jedisPool.getResource()) {
            jedis.expireAt(key, expireDate.getTime() / 1000);
        }
    }
}
